﻿using DX;
using DX.Behaviors;
using DX.ViewModels;
using DX.Views;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tools.Views;

namespace Tools.ViewModels
{
    [ViewType(typeof(MainForm))]
    [ViewType(typeof(MacOSMainForm), "MacOS")]
    [ViewType(typeof(OfficeMainForm), "Office")]
    public partial class MainViewModel : ViewModel, IMainView
    {
        public MainViewModel(IMessageCenter messageCenter, IManifestFileService manifestFileService)
        {
            Title = "小工具";
            this.messageCenter = messageCenter;
            this.manifestFileService = manifestFileService;
        }

        private readonly IMessageCenter messageCenter;
        private readonly IManifestFileService manifestFileService;

        protected override async Task<bool> OnCanClose()
        {
            return await messageCenter.Confirmation("是否退出");
        }

        protected override void OnAttach(IView view, IViewModel viewModel)
        {
            base.OnAttach(view, viewModel);
            if (view is ILoadPluginsBehavior pluginsBehavior) LoadPlugins(pluginsBehavior);
        }
        private void LoadPlugins(ILoadPluginsBehavior pluginsBehavior)
        {
            var list = manifestFileService.Deserialize<PluginProfile[]>("Tools.Plugins.json");
            if (list == null)
            {
                return;
            }
            List<string> strings = new List<string>();
            foreach (var profile in list)
            {
                var viewModelType = Type.GetType(profile.Type);
                if (viewModelType == null)
                {
                    strings.Add(profile.Name);
                    continue;
                }
                pluginsBehavior.AddPlugins(profile, (sender, e) =>
                {
                    //先执行Behavior中写的事件
                    //后执行这个事件
                    Console.WriteLine("11");
                });
            }
            if (strings.Count <= 0)
            {
                return;
            }
            var names = string.Join(",", strings);
            messageCenter.Show($"以下组件加载失败，{names}");
        }
    }

}
